#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <ctype.h>
#include <poll.h>

#define SERVER_PORT 8899

#define POLL_FD_MAX 1024
int main()
{

    // 创建套接字
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);

    // 填充套接字
    int sockaddrLen = sizeof(struct sockaddr_in);
    struct sockaddr_in serverAddr;
    memset(&serverAddr, 0, sockaddrLen);
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
    serverAddr.sin_port = htons(SERVER_PORT);

    // 绑定套接字
    bind(sockfd, (struct sockaddr *)&serverAddr, sockaddrLen);

    // 监听套接字
    listen(sockfd, 100);

    // 初始 pollfd 结构体
    struct pollfd allfd[POLL_FD_MAX];
    for (int i = 0; i < POLL_FD_MAX; ++i)
    {
        allfd[i].fd = -1;
    }
    // 设置 pollfd 监听是否有新客户端链接请求
    allfd[0].fd = sockfd;
    allfd[0].events = POLLIN;

    int maxfd = 0;
    while (1)
    {
        int i = 0;
        int ret = poll(allfd, maxfd + 1, -1);
        if (ret == -1)
        {
            perror("poll error: ");
            exit(EXIT_FAILURE);
        }

        if (allfd[0].revents & POLLIN)      // 有新客户端链接
        {
            int cfd = accept(sockfd, NULL, NULL);
            printf("[%s:%d] Accept fd %d\n", __FILE__, __LINE__, cfd);
            for (i = 1; i < POLL_FD_MAX; ++i)
            {
                if (allfd[i].fd == -1)
                {
                    allfd[i].fd = cfd;
                    
                    break;
                }
            }

            maxfd = maxfd < i ? i : maxfd;
        }
        allfd[i].events = POLLIN;   // 将新连接客户端加入到 poll 监听事件

        for (i = 1; i < maxfd + 1; ++i)
        {
            if (allfd[i].fd == -1)
            {
                continue;
            }

            if (allfd[i].revents & POLLIN)      // 检测客户端是否有新消息
            {
                char buf[1024] = {0};
                int len = recv(allfd[i].fd, buf, 1024, 0);
                if (len == -1)
                {
                    perror("recv error: ");
                    exit(EXIT_FAILURE);
                }
                else if (len == 0)
                {
                    close(allfd[i].fd);
                    allfd[i].fd = -1;
                    printf("Clinet leave\n");
                }
                else
                {
                    printf("recv msg: %s\n", buf);

                    send(allfd[i].fd, buf, len, 0);
                }
            }
        }
    }

    close(sockfd);

    return 0;
}